import { createApp } from 'vue';
import vant from 'vant';
import ArcoVue from '@arco-design/web-vue';
import ArcoVueIcon from '@arco-design/web-vue/es/icon';
import globalComponents from '@/components';
import store, { useDictStore, useUserStore } from '@/store';
import { hasToken, setToken, goLogin } from '@/utils/auth';
import { getLocationSearch, delLocationSearch, getUrl } from '@/utils';
import { apiGetToken } from '@/api/auth/index';
import router from './router';
import directive from './directive';
import App from './App.vue';
import './utils/rem';

import '@arco-design/web-vue/dist/arco.less';
import 'vant/lib/index.css';
import '@/assets/style/global.less';

const initAppInfo = async () => {
  const app = createApp(App);
  app.use(store);
  window.VueApp = app;

  app.use(vant);
  app.use(ArcoVue, {});
  app.use(ArcoVueIcon);
  app.use(globalComponents);
  app.use(directive);

  const userType: any =
    getLocationSearch('userType') ||
    localStorage.getItem('userType') ||
    'normal';

  if (userType) {
    localStorage.setItem('userType', userType);
    useUserStore().setInfo({
      userType,
    });
  }

  const code = getLocationSearch('code');
  const state = getLocationSearch('state');

  if (code) {
    setToken(code);
    const params = delLocationSearch(['code', 'state']);
    const url = `${getUrl()}?${params}`;
    window.location.replace(url);
    try {
      const res = await apiGetToken({
        code,
        state,
      });
      setToken(res.data.access_token.accesstoken);
    } catch (error) {
      console.log('🚀 ~ initAppInfo ~ error:', error);
    }
  }

  if (hasToken()) {
    await useUserStore().getUserInfo();
    useDictStore().getKeys();
    app.use(router);
    app.mount('#app');
  } else {
    goLogin();
  }
};

initAppInfo();
